data{
  int<lower=1> P;//party(Common to both data)
  int<lower=1> J;//item(CHES)
  int<lower=1> J_p;//item(POPPA)
  int<lower=1> I;//respondent(CHES)
  int<lower=1> I_p;//respondent(POPPA)
  int<lower=1> K;//dim
  real delta[P,J,I];//data matrix(CHES)
  real delta_p[P,J_p,I_p];//data matrix(POPPA)
  real obs_data[P,J,I];//observed data(CHES)
  real obs_data_p[P,J_p,I_p];//observed data(CHES)
}

parameters{
  vector[J-1] Z_raw[K];
  vector[J_p-1] Z_raw_p[K];
  vector[P] X[K];//Political party coordinates parameters (common)
  vector<lower=0>[K] sigx;//Common in the two data
	real<lower=0> sigd;
	real<lower=0> sigd_p;//POPPA
}

transformed parameters{
  vector[J] Z[K];
  vector[J_p] Z_p[K];
  for(k in 1:K){
    Z[k] = append_row(Z_raw[k], -sum(Z_raw[k]));
  }
  for(k in 1:K){
    Z_p[k] = append_row(Z_raw_p[k], -sum(Z_raw_p[k]));
  }
}

model{
  //CHES
  for(i in 1:I){
    for(j in 1:J){
      for(p in 1:P){
        real temp = 0;
        if(obs_data[p,j,i] == 1){
          for(k in 1:K){
            temp += (X[k][p]-Z[k][j])^2;
          }
          delta[p,j,i] ~ normal(sqrt(temp),sigd);
        }
      }
    }
  }
  //POPPA
  for(i_p in 1:I_p){
    for(j_p in 1:J_p){
      for(p in 1:P){
        real temp_p = 0;
        if(obs_data_p[p,j_p,i_p] == 1){
          for(k in 1:K){
            temp_p += (X[k][p]-Z_p[k][j_p])^2;
          }
          delta_p[p,j_p,i_p] ~ normal(sqrt(temp_p),sigd_p);
        }
      }
    }
  }
  //prior
  sigx ~ cauchy(0,2.5);
	sigd ~ cauchy(0,2.5);
	sigd_p ~ cauchy(0,2.5);
	for(k in 1:K) Z_raw[k] ~ normal(0,5);
	for(k in 1:K) Z_raw_p[k] ~ normal(0,5);
  for(k in 1:K) X[k] ~ normal(0, sigx[k]);
}

